// pages/batteryStatistics/batteryStatistics.js

const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import * as echarts from '../../ec-canvas/echarts';
const util = require('../../utils/util');
//去掉尾部的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;
//图表对象
let Chart1=null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图表
    ec1: {
      //延迟加载
      lazyLoad: true
    },
    //是否显示图表（避免遮挡）
    showChart:true,
    //无数据
    showNoData:true,
    //图表配置
    chartSet1:{
      //颜色
      barColor:'#FF3300',
      //轴上标题
      ytitle:'电压（V）',
      xtitle: '小时',
    },
    //传参来的设备编号
    equipmentNo:'',
    //传参来的物联网编号
    imei:'',
    //今日日期
    todayDate:util.timeFormatDay(new Date()),
    //日期选择框
    showDate:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    //显示的日期
    currentDateStr:util.timeFormatDay(new Date()),
    //日统计到几天前
    dayNum:7
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //设置日统计的最小日期
    this.getBeforeDate();

    if(options.detail){
      let obj=JSON.parse(options.detail);
      this.setData({
        equipmentNo:obj.equipmentNo,
        imei:obj.imei
      })

      //获取电池数据
      this.getChartData();
    }
  },

  //获取电池数据
  getChartData(){
    //图表组件
    this.echartsComponnet1 = this.selectComponent('#mychart1');

    this.setData({
      showNoData:false,
      showChart: true
    })

    let chartData={
      xData:[],
      yData:[
        {
          type: 'line',
          data: [],
          color: '#22884F'
        }
      ]
    }

    let param={
      "source":"小程序，设备列表，查询电池变化",
      "className": "com.jbn.model.iot.IotVolRecord",
      "condition": [
        {
          "fieldName": "createTime",
          "dataType": "date",
          "relation": ">=",
          "value": this.data.currentDateStr+' 00:00:00'
        },
        {
          "fieldName": "createTime",
          "dataType": "date",
          "relation": "<=",
          "value": this.data.currentDateStr+' 23:59:59'
        },
        {
          "fieldName": "imei",
          "relation": "=",
          "value": this.data.imei
        }
      ],
      "checkDataAuthority": false,
      "sortField": "_id",
      "sortDirection": "asc",
      "statisticsModel": {
        "operate":"avg",
        "unwind":"vol",
        "groupField": "vol.ctm",
        "groupFieldType": "date",
        "staField": "vol.vol",
        "staType": "Double",
        "groupDateType": "hour",
        "projectField": [
            "_id",
            "vol",
            "createTime",
            "imei"
        ]
      }
    }

    CommonService.findList(param).then(res=>{
      if(res.data.data){
        let result=res.data.data;
        console.log('电池变化数据');
        console.log(result);

        if(result.length){
          this.setData({
            showNoData:false,
            showChart: true
          })

          let xData=[],yData=[];
          result.forEach(item => {
            xData.push(parseInt(item._id.slice(11)));
            yData.push((item.staResult.toFixed(1)).replace(regexp,'$1'));
          });

          chartData={
            xData:xData,
            yData:[
              {
                type: 'line',
                data: yData,
                color: '#22884F'
              }
            ]
          }

          //判断图表是否第一次绘制
          this.isHaveChart(Chart1,this.echartsComponnet1,this.data.chartSet1,chartData);

        }else{
          this.setData({
            showNoData:true,
            showChart: false
          })
        }
      }else{
        this.setData({
          showNoData:true,
          showChart: false
        })
      }
    }).catch((error) => {
      this.setData({
        showNoData:true,
        showChart: false
      })
    })
  },

  //显示日期选择框
  onShowDate(){
    this.setData({
      showDate: true
    })
    //隐藏图表
    this.hideChart();
  },

  //关闭日期选择框
  onCloseDate(){
    this.setData({
      showDate: false
    })
    //显示图表
    this.showChart();
  },

  //确定日期时
  onConfirmDate(event){
    this.setData({
      currentDate: event.detail,
      currentDateStr:util.timeFormatDay(event.detail)
    })

    //关闭日期选择框
    this.onCloseDate();

    //获取电池数据
    this.getChartData();
  },

  //设置日统计的最小日期
  getBeforeDate(){
    let rusult=util.countPrevDay(new Date(),this.data.dayNum);
    this.setData({
      minDate: rusult
    });
  },


  //判断图表是否第一次绘制
  isHaveChart(chartObj,componnetObj,setObj,dataObj){
    if (!chartObj){
      //如果是第一次绘制，则初始化图表
      this.init_echarts(chartObj,componnetObj,setObj,dataObj);
    }else{
      //更新图表数据
      this.setOption(chartObj,setObj,dataObj);
    }
  },

  //初始化图表
  init_echarts: function (chartObj,componnetObj,setObj,dataObj) {
    componnetObj.init((canvas, width, height) => {
      chartObj = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      this.setOption(chartObj,setObj,dataObj);

      return chartObj;
    });
  },

  //更新图表数据
  setOption: function (chartObj,setObj,dataObj) {
    //清除
    chartObj.clear();
    //设置新数据
    chartObj.setOption(this.getOption(chartObj,setObj,dataObj));
  },

  //指定图表的配置项和数据
  getOption: function (chartObj,setObj,dataObj) {
    //文字颜色
    let fontColor='#666';

    let option = {
      legend: {
        //icon: 'arrow',
        textStyle: {
          color: '#666',
          padding: [0, 30, 0, 0]
        },
        x: 'right',
        y: 'top'
      },
      grid: {
        left: '5%',
        right: '12%',
        top: '20%',
        bottom: '7%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        name: setObj.xtitle,
        axisLabel: {
          //show: false,
          color: fontColor,
          fontSize : 14,
          //interval:2,
          //rotate:10
        },
        axisLine: {
          lineStyle: {
            color: setObj.barColor
          }
        },
        data: dataObj.xData,
      },
      yAxis: {
        type: 'value',
        name: setObj.ytitle,
        axisLabel: {
          //show: false,
          color: fontColor,
          fontSize : 13,
        },
        axisLine: {
          lineStyle: {
            color: setObj.barColor
          }
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      series:dataObj.yData
    };

    return option;
  },

  //隐藏图表
  hideChart(){
    this.setData({
      showChart:false
		})
  },

  //显示图表
  showChart(){
    this.setData({
      showChart:true
		})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
